package com.spirngboot.middleware.middleware_rabbitmq.server.rabbitmq.work.polling;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class Consumer {
    private static final Logger log = LoggerFactory.getLogger(Consumer.class);
    private static Runnable runnable = () -> {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.24.87.40");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("Guet@207");
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;

        try {
            //2.创建连接Connection
            String connectName = "生产者";
            connection = connectionFactory.newConnection(connectName);
            log.info("创建连接成功,连接名:{},连接:{}",connectName, connection.toString());
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            log.info("创建通道成功,通道名:{}",channel.toString());
            //4.通过创建交换机,声明队列,绑定关系,路由key,发送信息和接收信息
            String queueName = "queue1";
            channel.basicConsume(queueName, true,
                    (consumerTag, message) -> {
                        log.info("[{}]收到的消息是{}", Thread.currentThread().getName(), new String(message.getBody(), StandardCharsets.UTF_8));
                        //延时1s
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    },
                    consumerTag -> log.warn("接收消息失败")
            );
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //7.关闭通道
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //8.关闭连接
        if (connection != null && connection.isOpen()) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static void main(String[] args) {
        new Thread(runnable,"aaaaaa").start();
    }
}
